export enum FormatsEnums {
    YMD = 'Ymd',
    Y_M_D = 'Y-m-d',
    Y_M_D_H_I_S = 'Y-m-d H:i:s',
    H_I_S = 'H:i:s',
    I_S = 'i:s',
    _YMD = 'Y年m月d日',
    _YMDHIS = 'Y年m月d日 H时i分'
}

const zero = function (value: number): string | number {
    if (value < 10) {
        return '0' + value;
    }
    return value;
};

export const dateFormat = function (timestamp?: number, formats?: FormatsEnums): string {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || FormatsEnums.Y_M_D_H_I_S;

    const myDate = timestamp ? new Date(timestamp) : new Date();

    const year = myDate.getFullYear();
    const month = zero(myDate.getMonth() + 1);
    const day = zero(myDate.getDate());

    const hour = zero(myDate.getHours());
    const minite = zero(myDate.getMinutes());
    const second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function (matches: string): any {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
};

export const timeCostFormat = function (timeCost: number): string {
    const hour = Math.floor(timeCost / 3600);
    timeCost -= hour * 3600;
    const h = zero(hour);
    const minute = Math.floor(timeCost / 60);
    timeCost -= minute * 60;
    const m = zero(minute);
    const s = zero(timeCost);

    let formats = hour > 0 ? FormatsEnums.H_I_S : FormatsEnums.I_S;

    return formats.replace(/H|i|s/ig, function (matches: string): any {
        return ({
            H: h,
            i: m,
            s: s
        })[matches];
    });
};

function baseEnumFilter(data: string, useIdx: number = 1) {
    let isNumber = isNaN(parseFloat(data));
    return useIdx == 1 ? isNumber : !isNumber;
}
export const enumKeys = function (data: any, useIdx: number = 0) {
    let keys = Object.keys(data);
    if (useIdx > 0) {
        for (let i = keys.length - 1; i >= 0; i--) {
            if (!baseEnumFilter(keys[i], useIdx)) {
                keys.splice(i, 1);
            }
        }
    }
    return keys;
}

export const stringFormat = function (format: string, ...args: any[]): string {
    return format.replace(/{(\d+)}/g, (match, index) => {
        const argIndex = parseInt(index, 10);
        if (argIndex < 0 || argIndex >= args.length) {
            throw new Error(`Argument index out of range: ${index}`);
        }
        return args[argIndex];
    });
}